package com.itbaima.csmall.order.webapi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itbaima.csmall.cart.service.CartService;
import com.itbaima.csmall.commons.exception.CoolSharkServiceException;
import com.itbaima.csmall.commons.pojo.order.dto.OrderAddDTO;
import com.itbaima.csmall.commons.pojo.order.entity.Order;
import com.itbaima.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import com.itbaima.csmall.commons.restful.JsonPage;
import com.itbaima.csmall.commons.restful.ResponseCode;
import com.itbaima.csmall.order.service.OrderService;
import com.itbaima.csmall.order.webapi.mapper.OrderMapper;
import com.itbaima.csmall.stock.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>订单业务实现类</p>
 *
 * @author Chen
 * @since 2023/2/20 12:44:44
 */
@Slf4j
@Service
@DubboService
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @DubboReference
    private StockService stockService;
    @DubboReference
    private CartService cartService;

    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        // 1.这里先要减少订单中商品的库存数(调用stock减少库存的方法)
        StockReduceCountDTO stockReduceCountDTO = new StockReduceCountDTO();
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockService.reduceCommodityCount(stockReduceCountDTO);
        // 2.还要从购物车列表中删除用户选中的商品(调用cart模块删除购物车中商品的方法)
        cartService.deleteUserCart(orderAddDTO.getUserId(), orderAddDTO.getCommodityCode());

        // 模拟随机抛出异常，测试Seata分布式事务管理
        if (Math.random() < 0.5) {
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "发生随机异常");
        }

        // 3.新增订单信息
        Order order = new Order();
        BeanUtils.copyProperties(orderAddDTO, order);
        // 执行新增
        orderMapper.insertOrder(order);
        log.info("新增订单信息为:{}", order);
    }

    /**
     * 分页查询所有订单信息的方法
     *
     * @param page     页码
     * @param pageSize 每页条数
     * @return 分页查询的数据
     */
    @Override
    public JsonPage<Order> getAllOrdersByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Order> list = orderMapper.findAllOrders();
        // PageInfo中包含查询需要的分页信息
        return JsonPage.restPage(new PageInfo<>(list));
    }

}
